# from proc_email.prompt_paper import txt
import sys
import pandas as pd

sys.path.append("/data_ext/wxauto")
from tools.openai_tools import client
import json
from tools.send_dingtalk import request_send_text_msg
from proc_email.get_email_info import get_emails_to_csv


def get_paper_info(txt):
    msg = [
        {
            "role": "system",
            "content": """你是一个订阅邮件的信息抽取工具，将邮件中的关键信息保存为json.
            
        请从邮件的PAPERS部分抽取如下关键信息：
        论文大类、论文小类、论文链接、论文标题、论文简介、论文浏览量.
        并将标题、简介翻译成中文。
        
        然后按照文章对AI发展的核心价值推荐阅读顺序，并给出推荐理由~
        
        在最后对本期推荐的论文进行一个核心主题概述，提炼论文共性或者对AI领域的核心突破。
        
        具体字段名称和含义如下：
        
        {"items": [{
            "main_cat": 论文大类，如果没有请置空串
            "sub_cat": 论文小类，如果没有请置空串
            "paper_url": 论文链接，
            "title": 文章标题，
            "title_ch": 文章中文标题，
            "description": 文章简介内容，
            "description_ch": 文章中文简介，
            "views": 论文阅读量，
            "recommend_score": 推荐阅读分数，0-100，分数越高越值得阅读,
            "recommend_reason": 推荐理由
        }],
        "summary": "本期推荐几篇论文的核心主题概述以及对AI领域的核心突破",
        }
        """,
        },
        {
            "role": "user",
            "content": txt,
        },
    ]
    response = client.chat.completions.create(
        model="gpt-4.1",
        messages=msg,
        response_format={"type": "json_object"},
        temperature=0,
    )
    res_cont = response.choices[0].message.content
    # print(res_cont)
    res_json = json.loads(res_cont)
    print(res_json)
    return res_json


source_email = "contact@alphaxiv.org"
csv_file = f"/data_ext/wxauto/proc_email/data/{source_email}.csv"
get_emails_to_csv(source_email, csv_filename=csv_file)
dt = pd.to_datetime("now").strftime("%Y%m%d")


A = pd.read_csv(csv_file)
txt = A.iloc[-1]["内容"]
print(txt)
res_json = get_paper_info(txt)
print(res_json)
df = pd.DataFrame.from_dict(res_json["items"])
df["summary"] = res_json["summary"]
paper_file = f"data/email/paper/df_paper_v2_{dt}.csv"
df.to_csv(paper_file)


B = pd.read_csv(paper_file)
B = B.sort_values(by="views", ascending=False)
row = B.iloc[0]
n = len(B)
txt = f"""📚 {dt}期-AlphaXiv文章推荐：
核心概述：{row['summary']}\n
"""
icon_arr = ["1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", "6️⃣", "7️⃣", "8️⃣", "9️⃣"]


for i in range(n):
    row = B.iloc[i]
    txt += f"{icon_arr[i]} {row['title_ch']}\n"
    txt += f"📄 原文标题: {row['title']}\n"
    txt += f"💡 核心贡献: {row['description_ch']}\n"
    txt += f"🔗 论文链接: {row['paper_url']}\n"
    txt += f"🔥 阅读量: {row['views']}\n"
    txt += f"🧠 推荐理由: {row['recommend_reason']}\n\n"
print(txt)
request_send_text_msg(text=txt)
